<template>
  <div class="appointment-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="container">
        <h1 class="page-title">预约挂号</h1>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/portal' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/portal/patient' }">患者服务</el-breadcrumb-item>
          <el-breadcrumb-item>预约挂号</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>
    
    <!-- 主要内容 -->
    <div class="container main-content">
      <el-row :gutter="30">
        <!-- 左侧导航 -->
        <el-col :xs="24" :sm="24" :md="6" :lg="6" :xl="5">
          <div class="side-nav">
            <h3 class="side-nav-title">患者服务</h3>
            <el-menu
              class="side-menu"
              :default-active="activeMenu"
              @select="handleMenuSelect"
            >
              <el-menu-item index="appointment">
                <el-icon><Calendar /></el-icon>
                <span>预约挂号</span>
              </el-menu-item>
              <el-menu-item index="appointments">
                <el-icon><List /></el-icon>
                <span>我的预约</span>
              </el-menu-item>
              <el-menu-item index="records">
                <el-icon><Document /></el-icon>
                <span>就诊记录</span>
              </el-menu-item>
              <el-menu-item index="reports">
                <el-icon><DataAnalysis /></el-icon>
                <span>检查报告</span>
              </el-menu-item>
              <el-menu-item index="payment">
                <el-icon><Money /></el-icon>
                <span>费用查询</span>
              </el-menu-item>
              <el-menu-item index="prescription">
                <el-icon><List /></el-icon>
                <span>处方查询</span>
              </el-menu-item>
            </el-menu>
            
            <div class="service-card">
              <h3 class="service-card-title">
                <el-icon><Service /></el-icon> 服务热线
              </h3>
              <p class="service-phone">123-456-7890</p>
              <p class="service-time">周一至周日 8:00-18:00</p>
            </div>
          </div>
        </el-col>
        
        <!-- 右侧内容 -->
        <el-col :xs="24" :sm="24" :md="18" :lg="18" :xl="19">
          <div class="appointment-content">
            <!-- 预约提示 -->
            <el-alert
              title="温馨提示：请至少提前1天预约，同一科室每天限约1次"
              type="info"
              :closable="false"
              show-icon
              class="alert-info"
            >
              <template #default>
                <p>1. 请确保个人信息真实有效，否则将无法正常就诊</p>
                <p>2. 预约成功后，请在预约时间前30分钟到医院报到</p>
                <p>3. 如需取消预约，请提前12小时操作，避免影响他人就诊</p>
              </template>
            </el-alert>
            
            <!-- 预约步骤 -->
            <div class="appointment-steps">
              <el-steps :active="activeStep" finish-status="success">
                <el-step title="选择科室医生" description="选择您要就诊的科室和医生"></el-step>
                <el-step title="选择就诊时间" description="选择合适的就诊日期和时间段"></el-step>
                <el-step title="填写就诊信息" description="填写患者基本信息和病情描述"></el-step>
                <el-step title="确认预约信息" description="核对并确认预约信息"></el-step>
              </el-steps>
            </div>
            
            <!-- 步骤内容 -->
            <div class="step-content">
              <!-- 步骤1：选择科室医生 -->
              <div v-if="activeStep === 0" class="step-container">
                <h2 class="step-title">选择科室和医生</h2>
                
                <el-form :model="appointmentForm" label-width="100px">
                  <el-form-item label="就诊类型">
                    <el-radio-group v-model="appointmentForm.visitType" @change="handleVisitTypeChange">
                      <el-radio 
                        v-for="type in availableVisitTypes" 
                        :key="type.value" 
                        :label="type.value"
                      >
                        {{ type.label }}
                      </el-radio>
                    </el-radio-group>
                    <div v-if="availableVisitTypes.length === 0" class="no-visit-type-tip">
                      暂无可用就诊类型，请选择科室和医生后查看
                    </div>
                  </el-form-item>
                  
                  <el-form-item label="选择科室">
                    <el-cascader
                      v-model="appointmentForm.department"
                      :options="departmentOptions"
                      :props="{ 
                        expandTrigger: 'hover',
                        separator: ' / '  
                      }"
                      placeholder="请选择科室"
                      clearable
                      @change="handleDepartmentChange"
                      class="full-width-cascader"
                    ></el-cascader>
                  </el-form-item>
                </el-form>
                
                <!-- 医生列表 -->
                <div class="doctor-list" v-if="doctorList.length > 0">
                  <h3 class="section-subtitle">
                    {{ getDepartmentName(appointmentForm.department) }}可预约医生（{{ doctorList.length }}名）
                  </h3>
                  
                  <el-row :gutter="20">
                    <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8" v-for="doctor in doctorList" :key="doctor.id">
                      <div 
                        class="doctor-card" 
                        :class="{ 'doctor-card-selected': appointmentForm.doctorId === doctor.id }"
                        @click="selectDoctor(doctor)"
                      >
                        <div class="doctor-avatar">
                          <el-avatar :size="80" :src="doctor.image"></el-avatar>
                        </div>
                        <div class="doctor-info">
                          <h3 class="doctor-name">
                            {{ doctor.name }}
                          </h3>
                          <p class="doctor-title">{{ doctor.title }}</p>
                          <p class="doctor-specialty">{{ doctor.specialty }}</p>
                          <div class="doctor-rating">
                            <el-rate
                              v-model="doctor.rating"
                              disabled
                              text-color="#ff9900"
                              score-template="{value}"
                            ></el-rate>
                          </div>
                        </div>
                      </div>
                    </el-col>
                  </el-row>
                </div>
                
                <div class="step-actions">
                  <el-button type="primary" @click="nextStep" :disabled="!appointmentForm.doctorId">下一步</el-button>
                </div>
              </div>
              
              <!-- 步骤2：选择就诊时间 -->
              <div v-else-if="activeStep === 1" class="step-container">
                <h2 class="step-title">选择就诊时间</h2>
                
                <!-- 医生选择后的显示组件 -->
                <div class="doctor-selected">
                  <div class="doctor-selected-avatar">
                    <el-avatar 
                      :size="60" 
                      :src="selectedDoctor?.image || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"
                    ></el-avatar>
                  </div>
                  <div class="doctor-selected-info">
                    <h3 class="doctor-selected-name">
                      {{ selectedDoctor?.name || '未选择' }}
                    </h3>
                    <p class="doctor-selected-title">{{ selectedDoctor?.title || '' }}</p>
                    <p class="doctor-selected-dept">
                      {{ getDepartmentLabel(appointmentForm.department) }}
                    </p>
                  </div>
                  <div class="doctor-selected-action">
                    <el-button type="text" @click="changeDoctor">更换医生</el-button>
                  </div>
                </div>
                
                <!-- 日期选择 -->
                <div class="date-selection">
                  <h3 class="section-subtitle">选择就诊日期</h3>
                  
                  <div class="date-selector">
                    <div 
                      v-for="date in availableDates" 
                      :key="date.value"
                      class="date-item"
                      :class="{ 'date-selected': appointmentForm.appointmentDate === date.value, 'date-past': date.isPast }"
                      @click="selectDate(date)"
                    >
                      <div class="date-weekday">{{ date.weekday }}</div>
                      <div class="date-day">{{ date.day }}</div>
                      <div class="date-month">{{ date.month }}</div>
                      <div class="date-status" :class="getDateStatusClass(date)">
                        {{ getDateStatusText(date) }}
                      </div>
                    </div>
                  </div>
                </div>
                
                <!-- 时间段选择 -->
                <div class="time-selection" v-if="appointmentForm.appointmentDate">
                  <h3 class="section-subtitle">选择就诊时间段</h3>
                  
                  <div class="time-period">
                    <h4 class="period-title">上午</h4>
                    <div class="time-slots">
                      <div 
                        v-for="slot in morningSlots" 
                        :key="slot.value"
                        class="time-slot"
                        :class="{ 
                          'time-slot-selected': appointmentForm.appointmentTime === slot.value,
                          'time-slot-disabled': slot.disabled
                        }"
                        @click="!slot.disabled && selectTimeSlot(slot)"
                      >
                        <span class="time-text">{{ slot.label }}</span>
                        <span class="slot-status">{{ slot.disabled ? '已满' : '可约' }}</span>
                      </div>
                    </div>
                  </div>
                  
                  <div class="time-period">
                    <h4 class="period-title">下午</h4>
                    <div class="time-slots">
                      <div 
                        v-for="slot in afternoonSlots" 
                        :key="slot.value"
                        class="time-slot"
                        :class="{ 
                          'time-slot-selected': appointmentForm.appointmentTime === slot.value,
                          'time-slot-disabled': slot.disabled
                        }"
                        @click="!slot.disabled && selectTimeSlot(slot)"
                      >
                        <span class="time-text">{{ slot.label }}</span>
                        <span class="slot-status">{{ slot.disabled ? '已满' : '可约' }}</span>
                      </div>
                    </div>
                  </div>
                </div>
                
                <div class="step-actions">
                  <el-button @click="prevStep">上一步</el-button>
                  <el-button 
                    type="primary" 
                    @click="nextStep" 
                    :disabled="!appointmentForm.appointmentDate || !appointmentForm.appointmentTime"
                  >
                    下一步
                  </el-button>
                </div>
              </div>
              
              <!-- 步骤3：填写就诊信息 -->
              <div v-else-if="activeStep === 2" class="step-container">
                <h2 class="step-title">填写就诊信息</h2>
                
                <div class="appointment-summary">
                  <div class="summary-item">
                    <span class="summary-label">就诊科室：</span>
                    <span class="summary-value">{{ getDepartmentLabel(appointmentForm.department) }}</span>
                  </div>
                  <div class="summary-item">
                    <span class="summary-label">就诊医生：</span>
                    <span class="summary-value">{{ selectedDoctor?.name }} {{ selectedDoctor?.title }}</span>
                  </div>
                  <div class="summary-item">
                    <span class="summary-label">就诊时间：</span>
                    <span class="summary-value">{{ getDateLabel(appointmentForm.appointmentDate) }} {{ getTimeLabel(appointmentForm.appointmentTime) }}</span>
                  </div>
                </div>
                
                <el-divider></el-divider>
                
                <h3 class="section-subtitle">填写患者信息</h3>
                
                <el-form 
                  :model="appointmentForm" 
                  :rules="rules" 
                  ref="patientFormRef" 
                  label-width="100px"
                  class="patient-form"
                >
                  <el-form-item label="就诊人" prop="patientName">
                    <el-input v-model="appointmentForm.patientName" placeholder="请输入就诊人姓名" disabled></el-input>
                    <div class="form-item-tip">个人信息从用户资料获取，如需修改请前往个人中心</div>
                  </el-form-item>
                  
                  <el-form-item label="性别" prop="patientGender">
                    <el-radio-group v-model="appointmentForm.patientGender" disabled>
                      <el-radio :value="'male'">男</el-radio>
                      <el-radio :value="'female'">女</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  
                  <el-form-item label="手机号" prop="patientPhone">
                    <el-input v-model="appointmentForm.patientPhone" placeholder="联系电话" disabled></el-input>
                  </el-form-item>
                  
                  <el-form-item label="身份证号" prop="patientID">
                    <el-input v-model="appointmentForm.patientID" placeholder="身份证号" disabled></el-input>
                  </el-form-item>
                  
                  <el-form-item label="症状描述" prop="symptoms">
                    <el-input 
                      type="textarea" 
                      v-model="appointmentForm.symptoms" 
                      placeholder="请简要描述症状，方便医生提前了解情况"
                      :rows="4"
                    ></el-input>
                  </el-form-item>
                </el-form>
                
                <div class="step-actions">
                  <el-button @click="prevStep">上一步</el-button>
                  <el-button type="primary" @click="submitPatientInfo">下一步</el-button>
                </div>
              </div>
              
              <!-- 步骤4：确认预约信息 -->
              <div v-else-if="activeStep === 3" class="step-container">
                <h2 class="step-title">确认预约信息</h2>
                
                <div class="confirmation-card">
                  <div class="confirmation-header">
                    <el-icon class="confirmation-icon"><Calendar /></el-icon>
                    <h3 class="confirmation-title">预约信息确认</h3>
                  </div>
                  
                  <div class="confirmation-content">
                    <div class="confirmation-section">
                      <h4 class="confirmation-section-title">就诊信息</h4>
                      <div class="confirmation-item">
                        <span class="confirmation-label">就诊科室：</span>
                        <span class="confirmation-value">{{ getDepartmentLabel(appointmentForm.department) }}</span>
                      </div>
                      <div class="confirmation-item">
                        <span class="confirmation-label">就诊医生：</span>
                        <span class="confirmation-value">{{ selectedDoctor?.name }} {{ selectedDoctor?.title }}</span>
                      </div>
                      <div class="confirmation-item">
                        <span class="confirmation-label">就诊时间：</span>
                        <span class="confirmation-value">{{ getDateLabel(appointmentForm.appointmentDate) }} {{ getTimeLabel(appointmentForm.appointmentTime) }}</span>
                      </div>
                      <div class="confirmation-item">
                        <span class="confirmation-label">就诊类型：</span>
                        <span class="confirmation-value">{{ getVisitTypeLabel(appointmentForm.visitType) }}</span>
                      </div>
                    </div>
                    
                    <el-divider></el-divider>
                    
                    <div class="confirmation-section">
                      <h4 class="confirmation-section-title">患者信息</h4>
                      <div class="confirmation-item">
                        <span class="confirmation-label">姓名：</span>
                        <span class="confirmation-value">{{ appointmentForm.patientName }}</span>
                      </div>
                      <div class="confirmation-item">
                        <span class="confirmation-label">性别：</span>
                        <span class="confirmation-value">{{ appointmentForm.patientGender === 'male' ? '男' : '女' }}</span>
                      </div>
                      <div class="confirmation-item">
                        <span class="confirmation-label">手机号：</span>
                        <span class="confirmation-value">{{ appointmentForm.patientPhone }}</span>
                      </div>
                      <div class="confirmation-item">
                        <span class="confirmation-label">身份证号：</span>
                        <span class="confirmation-value">{{ appointmentForm.patientID }}</span>
                      </div>
                    </div>
                    
                    <div class="confirmation-section" v-if="appointmentForm.symptoms">
                      <h4 class="confirmation-section-title">症状描述</h4>
                      <p class="confirmation-text">{{ appointmentForm.symptoms }}</p>
                    </div>
                  </div>
                  
                  <div class="confirmation-footer">
                    <el-checkbox v-model="agreementChecked">我已阅读并同意《预约挂号服务条款》和《隐私保护政策》</el-checkbox>
                  </div>
                </div>
                
                <div class="step-actions">
                  <el-button @click="prevStep">上一步</el-button>
                  <el-button type="primary" @click="confirmAppointment" :disabled="!agreementChecked">确认预约</el-button>
                </div>
              </div>
              
              <!-- 预约成功 -->
              <div v-else-if="activeStep === 4" class="step-container">
                <div class="success-container">
                  <el-result
                    icon="success"
                    title="预约成功"
                    sub-title="您的预约申请已提交成功，请按时前往医院就诊"
                  >
                    <template #extra>
                      <div class="success-info">
                        <p><strong>预约号：</strong> {{ appointmentNumber }}</p>
                        <p><strong>就诊人：</strong> {{ appointmentForm.patientName }}</p>
                        <p><strong>就诊科室：</strong> {{ getDepartmentLabel(appointmentForm.department) }}</p>
                        <p><strong>就诊医生：</strong> {{ selectedDoctor?.name }} {{ selectedDoctor?.title }}</p>
                        <p><strong>就诊类型：</strong> {{ getVisitTypeLabel(appointmentForm.visitType) }}</p>
                        <p><strong>就诊时间：</strong> {{ getDateLabel(appointmentForm.appointmentDate) }} {{ getTimeLabel(appointmentForm.appointmentTime) }}</p>
                      </div>
                      <div class="success-actions">
                        <el-button type="primary" @click="navigateToAppointmentList">查看我的预约</el-button>
                        <el-button @click="navigateToHome">返回首页</el-button>
                      </div>
                    </template>
                  </el-result>
                </div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { departmentAPI, doctorAPI, appointmentAPI, patientAPI, scheduleAPI } from '@/utils/api'
import { format } from 'date-fns'

const router = useRouter()
const userStore = useUserStore()
const activeMenu = ref('appointment')
const activeStep = ref(0)
const patientFormRef = ref(null)
const agreementChecked = ref(false)
const appointmentNumber = ref('')
const loading = ref(false)

// 预约表单
const appointmentForm = reactive({
  visitType: '',  // 不再预设值，由医生排班决定
  department: [],
  doctorId: '',
  appointmentDate: '',
  appointmentTime: '',
  patientName: '',
  patientGender: '',
  patientPhone: '',
  patientID: '',
  symptoms: ''
})

// 表单验证规则
const rules = {
  // 个人基本信息不再需要验证，因为从用户信息中获取且不可修改
  patientName: [], // 不需要验证
  patientGender: [], // 不需要验证
  patientPhone: [], // 不需要验证
  patientID: [], // 不需要验证
  
  // 预约相关验证
  visitType: [{ required: true, message: '请选择就诊类型', trigger: 'change' }],
  department: [{ required: true, message: '请选择科室', trigger: 'change' }],
  doctorId: [{ required: true, message: '请选择医生', trigger: 'change' }],
  appointmentDate: [{ required: true, message: '请选择就诊日期', trigger: 'change' }],
  appointmentTime: [{ required: true, message: '请选择就诊时间', trigger: 'change' }],
  
  // 仅症状描述需要验证
  symptoms: [{ required: true, message: '请简要描述症状', trigger: 'blur' }]
}

// 科室选项
const departmentOptions = ref([])

// 医生列表
const doctorList = ref([])

// 选中的医生
const selectedDoctor = computed(() => {
  return doctorList.value.find(doctor => doctor.id === appointmentForm.doctorId) || null
})

// 可用日期
const availableDates = ref([])

// 上午时间段
const morningSlots = ref([])

// 下午时间段
const afternoonSlots = ref([])

// 就诊类型选项
const visitTypeOptions = ref([
  { value: 'expert', label: '专家门诊' },
  { value: 'specialist', label: '专科门诊' },
  { value: 'general', label: '普通门诊' }
])

// 当前可用的就诊类型（根据医生排班决定）
const availableVisitTypes = ref([])

// 加载科室列表
const loadDepartments = async () => {
  try {
    loading.value = true
    const res = await departmentAPI.getDepartments()
    
    if (res.success && res.data) {
      console.log('科室API响应:', res)
      
      // 处理部门数据为级联选择器格式
      const deptData = []
      
      // 检查数据格式，从不同位置提取科室列表
      let departments = []
      
      if (res.data.departments && Array.isArray(res.data.departments)) {
        // 标准格式
        departments = res.data.departments
      } else if (Array.isArray(res.data)) {
        // 直接返回数组的情况
        departments = res.data
      } else {
        // 如果是对象格式（如之前处理的mockData）
        departments = Object.values(res.data).filter(item => 
          typeof item === 'object' && item !== null && item.name && item.status === '启用'
        )
      }
      
      console.log('处理后的科室列表:', departments)
      
      // 对科室进行分类
      const categoryMap = {}
      
      // 将科室按类别分组
      departments.forEach(dept => {
        if (!dept) return
        
        const category = dept.category || '其他'
        
        // 过滤掉行政类科室
        if (category === '行政' || category.includes('行政')) return
        
        if (!categoryMap[category]) {
          categoryMap[category] = {
            id: category,
            value: category,
            label: category,
            children: []
          }
        }
        
        categoryMap[category].children.push({
          id: dept.id || dept._id,
          value: dept.id || dept._id,
          label: dept.name,
          status: dept.status
        })
      })
      
      // 将分类转换为数组
      for (const key in categoryMap) {
        deptData.push(categoryMap[key])
      }
      
      departmentOptions.value = deptData
      console.log('科室数据加载成功:', departmentOptions.value)
      
      if (departmentOptions.value.length === 0) {
        // 如果没有数据，可能是接口问题，使用模拟数据
        ElMessage.warning('科室数据加载异常，使用默认数据')
        useMockDepartments()
      }
    } else {
      ElMessage.warning('获取科室数据失败，使用默认数据')
      useMockDepartments()
    }
  } catch (error) {
    console.error('加载科室数据失败:', error)
    ElMessage.warning('获取科室数据失败，使用默认数据')
    useMockDepartments()
  } finally {
    loading.value = false
  }
}

// 使用模拟科室数据
const useMockDepartments = () => {
  const mockDepartments = [
    {
      id: '临床科室',
      value: '临床科室',
      label: '临床科室',
      children: [
        { id: '1', value: '1', label: '内科', status: '启用' },
        { id: '2', value: '2', label: '外科', status: '启用' },
        { id: '3', value: '3', label: '儿科', status: '启用' },
        { id: '4', value: '4', label: '妇产科', status: '启用' },
        { id: '5', value: '5', label: '眼科', status: '启用' },
        { id: '6', value: '6', label: '口腔科', status: '启用' },
        { id: '7', value: '7', label: '皮肤科', status: '启用' },
        { id: '8', value: '8', label: '神经科', status: '启用' }
      ]
    },
    {
      id: '医技科室',
      value: '医技科室',
      label: '医技科室',
      children: [
        { id: '9', value: '9', label: '检验科', status: '启用' },
        { id: '10', value: '10', label: '放射科', status: '启用' },
        { id: '11', value: '11', label: '超声科', status: '启用' },
        { id: '12', value: '12', label: '心电图室', status: '启用' }
      ]
    }
  ]
  
  departmentOptions.value = mockDepartments
  console.log('使用模拟科室数据')
}

// 加载医生列表
const loadDoctors = async (departmentId) => {
  if (!departmentId) return
  
  try {
    loading.value = true
    
    // 通过API获取指定科室的医生列表
    const res = await doctorAPI.getDoctors({ departmentId: departmentId })
    
    if (res.success && res.data && (res.data.doctors || res.data.items)) {
      // 适配不同的API返回格式
      const doctorsData = res.data.doctors || res.data.items || []
      
      // 处理医生数据
      doctorList.value = doctorsData.map(doctor => ({
        id: doctor.id,
        name: doctor.name,
        title: doctor.title || doctor.position || '医师',
        department: doctor.department?.name || appointmentForm.department[1],
        specialty: Array.isArray(doctor.specialties) ? doctor.specialties.join(', ') : doctor.specialty || '',
        rating: doctor.rating ? Number(doctor.rating) : Number((4 + Math.random()).toFixed(1)),
        appointmentCount: doctor.appointmentCount || Math.floor(Math.random() * 1000),
        image: doctor.avatar || doctor.image || generateDoctorAvatar(doctor.name)
      }))
      
      // 如果没有医生数据，显示提示
      if (doctorList.value.length === 0) {
        ElMessage.info('当前科室暂无可预约医生')
      }
      
      console.log('医生列表加载成功:', doctorList.value)
    } else if (res.success && res.data && res.data[departmentId]) {
      // 如果API返回了部门直接包含医生的数据格式
      const department = res.data[departmentId]
      
      if (department.doctors && Array.isArray(department.doctors)) {
        doctorList.value = department.doctors.map(doctor => ({
          id: doctor.id,
          name: doctor.name,
          title: doctor.title || '医师',
          department: department.name,
          specialty: Array.isArray(doctor.specialties) ? doctor.specialties.join(', ') : '',
          rating: Number((4 + Math.random()).toFixed(1)),
          appointmentCount: Math.floor(Math.random() * 1000),
          image: doctor.avatar || generateDoctorAvatar(doctor.name)
        }))
        
        console.log('从部门数据中提取医生列表成功:', doctorList.value)
      } else {
        ElMessage.warning('未找到医生数据')
        doctorList.value = []
      }
    } else {
      // 如果API请求成功但没有数据，使用模拟数据
      generateMockDoctors(departmentId)
    }
  } catch (error) {
    console.error('加载医生列表失败:', error)
    // 出错时使用模拟数据
    generateMockDoctors(departmentId)
  } finally {
    loading.value = false
  }
}

// 生成模拟医生数据（作为后备方案）
const generateMockDoctors = (departmentId) => {
  console.log('使用模拟医生数据')
  
  const specialties = {
    '1': ['内科', '心血管内科', '消化内科', '呼吸内科'],
    '2': ['外科', '普通外科', '神经外科', '胸外科'],
    '3': ['儿科', '儿童保健', '新生儿科'],
    '4': ['妇产科', '产科', '妇科'],
    '5': ['眼科', '屈光科', '眼底病科'],
    '6': ['口腔科', '口腔正畸', '口腔修复'],
    '7': ['皮肤科', '皮肤病', '性病科'],
    '8': ['精神科', '心理科', '精神心理科']
  }
  
  const deptSpecialties = specialties[departmentId] || ['常规诊疗']
  
  // 为科室生成3-5名医生
  const count = Math.floor(Math.random() * 3) + 3
  const mockDoctors = []
  
  const titles = ['主任医师', '副主任医师', '主治医师', '住院医师']
  const firstNames = ['张', '王', '李', '赵', '刘', '陈', '杨', '吴', '孙', '周']
  
  for (let i = 0; i < count; i++) {
    const firstName = firstNames[Math.floor(Math.random() * firstNames.length)]
    const name = `${firstName}医生${i + 1}`
    const title = titles[Math.floor(Math.random() * titles.length)]
    const specialty = deptSpecialties[Math.floor(Math.random() * deptSpecialties.length)]
    
    mockDoctors.push({
      id: `mock-doctor-${departmentId}-${i}`,
      name: name,
      title: title,
      department: departmentId,
      specialty: specialty,
      rating: Number((4 + Math.random()).toFixed(1)),
      appointmentCount: Math.floor(Math.random() * 1000),
      image: generateDoctorAvatar(name)
    })
  }
  
  doctorList.value = mockDoctors
}

// 生成医生头像
const generateDoctorAvatar = (name) => {
  // 根据姓名生成一个简单的占位头像URL
  const firstChar = name ? name.charAt(0) : 'D'
  const colors = ['1abc9c', '3498db', '9b59b6', 'f1c40f', 'e67e22', 'e74c3c', '34495e']
  const colorIndex = Math.abs(name.charCodeAt(0)) % colors.length
  
  return `https://ui-avatars.com/api/?name=${firstChar}&background=${colors[colorIndex]}&color=fff&size=100`
}

// 选择科室时加载医生
const handleDepartmentChange = (value) => {
  if (!value || value.length < 2) return
  
  // 获取选中的科室ID（第二级）
  const departmentId = value[1]
  appointmentForm.doctorId = '' // 清空医生选择
  // 不需要手动设置计算属性的值，它会自动响应doctorId的变化
  
  // 加载选中科室的医生列表
  loadDoctors(departmentId)
}

// 生成可预约日期
const generateAvailableDates = async (doctorId) => {
  loading.value = true
  try {
    // 计算前一周和后一周的日期
    const today = new Date()
    const oneWeekAgo = new Date(today)
    oneWeekAgo.setDate(today.getDate() - 7)
    const oneWeekLater = new Date(today)
    oneWeekLater.setDate(today.getDate() + 7)
    
    console.log('获取排班日期范围:', oneWeekAgo.toISOString().split('T')[0], '至', oneWeekLater.toISOString().split('T')[0])
    
    // 从API获取医生排班信息，查询范围为前后一周
    const res = await scheduleAPI.getSchedules({ 
      doctorId: doctorId,
      startDate: oneWeekAgo.toISOString().split('T')[0], // 从一周前开始
      endDate: oneWeekLater.toISOString().split('T')[0], // 到一周后结束
      limit: 14 // 获取前后一周的排班（共14天）
    })
    
    console.log('排班API响应:', res)
    
    // 检查响应是否成功且包含排班数据
    if (res.success && res.data && res.data.schedules && res.data.schedules.length > 0) {
      const schedules = res.data.schedules
      console.log('获取到的排班数据:', schedules)
      
      // 收集所有可用的就诊类型
      const visitTypes = new Set()
      
      // 按日期分组并统计每天可用预约数
      const schedulesMap = {}
      
      schedules.forEach(schedule => {
        // 处理日期格式，API返回的日期可能包含时间部分
        const dateStr = schedule.date ? 
                       (schedule.date.includes('T') ? schedule.date.split('T')[0] : schedule.date) : 
                       new Date().toISOString().split('T')[0]
        
        if (!schedulesMap[dateStr]) {
          schedulesMap[dateStr] = {
            date: dateStr,
            totalSlots: 0,
            availableSlots: 0,
            scheduleIds: [],
            registrationTypes: new Set() // 保存该日期的所有就诊类型
          }
        }
        
        // 处理registrationType
        const regType = schedule.registrationType
        let frontendType = ''
        
        // 映射后端注册类型到前端就诊类型
        if (regType === '普通门诊') {
          frontendType = 'general'
        } else if (regType === '专家门诊') {
          frontendType = 'expert'
        } else if (regType === '特需门诊') {
          frontendType = 'specialist'
        }
        
        // 计算总容量和剩余容量
        let totalCapacity = 0
        let remainingCapacity = 0
        
        // 从timeSlots中获取容量信息
        if (schedule.timeSlots && Array.isArray(schedule.timeSlots)) {
          schedule.timeSlots.forEach(slot => {
            totalCapacity += slot.capacity || 0
          })
        }
        
        // 从remainingCapacity中获取剩余容量
        if (schedule.remainingCapacity) {
          Object.values(schedule.remainingCapacity).forEach(value => {
            remainingCapacity += (typeof value === 'number') ? value : 0
          })
        }
        
        schedulesMap[dateStr].totalSlots += totalCapacity
        schedulesMap[dateStr].availableSlots += remainingCapacity
        schedulesMap[dateStr].scheduleIds.push(schedule.id)
        
        // 保存排班的就诊类型
        if (frontendType) {
          schedulesMap[dateStr].registrationTypes.add(frontendType)
          visitTypes.add(frontendType)
        }
      })
      
      console.log('按日期分组后的排班数据:', schedulesMap)
      
      // 更新可用就诊类型
      availableVisitTypes.value = Array.from(visitTypes).map(type => {
        // 根据前端类型代码获取标签
        let label = type
        if (type === 'general') {
          label = '普通门诊'
        } else if (type === 'expert') {
          label = '专家门诊'
        } else if (type === 'specialist') {
          label = '特需门诊'
        }
        
        return { value: type, label: label }
      })
      
      console.log('可用就诊类型:', availableVisitTypes.value)
      
      // 如果有可用的就诊类型但当前没有选择，则自动选择第一个
      if (availableVisitTypes.value.length > 0 && !appointmentForm.visitType) {
        appointmentForm.visitType = availableVisitTypes.value[0].value
      }
      
      // 转换为可用日期列表
      const dates = []
      
      // 生成从一周前到一周后的日期，共15天（包括今天）
      for (let i = -7; i <= 7; i++) {
        const date = new Date(today)
        date.setDate(today.getDate() + i)
        
        const dateStr = date.toISOString().split('T')[0]
        const scheduleInfo = schedulesMap[dateStr]
        
        // 检查是否是周末
        const isWeekend = date.getDay() === 0 || date.getDay() === 6
        
        // 检查是否有排班
        const hasSchedule = scheduleInfo && scheduleInfo.totalSlots > 0
        
        // 计算剩余容量
        const remaining = hasSchedule ? scheduleInfo.availableSlots : 0
        
        // 获取注册类型
        const registrationTypes = hasSchedule ? Array.from(scheduleInfo.registrationTypes) : []
        
        // 检查当前选择的就诊类型是否可用
        const hasSelectedVisitType = !appointmentForm.visitType || 
                                    (hasSchedule && registrationTypes.includes(appointmentForm.visitType))
        
        // 对于过去的日期，标记为不可用
        const isPast = date < new Date().setHours(0, 0, 0, 0)
        
        dates.push({
          value: dateStr,
          day: date.getDate(),
          month: `${date.getMonth() + 1}月`,
          weekday: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()],
          available: !isPast && hasSchedule && remaining > 0 && hasSelectedVisitType,
          remaining: remaining,
          scheduleIds: hasSchedule ? scheduleInfo.scheduleIds : [],
          registrationTypes: registrationTypes,
          isPast: isPast
        })
      }
      
      availableDates.value = dates
      console.log('可预约日期加载成功:', availableDates.value)
      return
    }
    
    // 如果API请求失败或没有排班数据，使用模拟数据
    console.log('没有获取到有效的排班数据，使用模拟数据')
    fallbackToMockDates()
  } catch (error) {
    console.error('加载可预约日期失败:', error)
    // 出错时使用模拟数据
    fallbackToMockDates()
  } finally {
    loading.value = false
  }
}

// 生成时间段
const generateTimeSlots = async (date, doctorId) => {
  if (!date || !doctorId) return
  
  loading.value = true
  try {
    console.log('获取时间段数据，日期:', date, '医生ID:', doctorId, '就诊类型:', appointmentForm.visitType)
    
    // 从API获取指定日期的医生排班详情
    const res = await scheduleAPI.getSchedules({
      doctorId: doctorId,
      date: date,
      registrationType: appointmentForm.visitType === 'expert' ? '专家门诊' : 
                         appointmentForm.visitType === 'general' ? '普通门诊' : 
                         appointmentForm.visitType === 'specialist' ? '特需门诊' : ''
    })
    
    console.log('时间段API响应:', res)
    
    // 检查响应是否成功且包含排班数据
    if (res.success && res.data && res.data.schedules && res.data.schedules.length > 0) {
      const schedules = res.data.schedules
      console.log('获取到的时间段排班数据:', schedules)
      
      // 提取上午和下午的时间段
      const morning = []
      const afternoon = []
      
      // 处理每个排班
      schedules.forEach(schedule => {
        // 检查是否有时间段数据
        if (schedule.timeSlots && Array.isArray(schedule.timeSlots)) {
          // 遍历时间段
          schedule.timeSlots.forEach(slot => {
            // 确定时段所属的时间段（上午/下午）
            const period = slot.period
            
            // 格式化时间
            const startTime = slot.startTime.includes(':') ? slot.startTime : `${slot.startTime}:00`
            const endTime = slot.endTime.includes(':') ? slot.endTime : `${slot.endTime}:00`
            
            // 检查剩余容量
            let remainingCapacity = 0
            if (schedule.remainingCapacity && schedule.remainingCapacity[period] !== undefined) {
              remainingCapacity = schedule.remainingCapacity[period]
            }
            
            // 创建时间段对象
            const slotObj = {
              value: `${startTime}-${endTime}`,
              label: `${startTime}-${endTime}`,
              disabled: remainingCapacity <= 0,
              slotId: `${schedule.id}-${period}`,
              period: period
            }
            
            // 根据时段分配到上午或下午
            if (period === '上午') {
              morning.push(slotObj)
            } else if (period === '下午') {
              afternoon.push(slotObj)
            }
          })
        }
      })
      
      console.log('处理后的时间段 - 上午:', morning, '下午:', afternoon)
      
      // 更新响应式数据
      morningSlots.value = morning
      afternoonSlots.value = afternoon
      
      return
    }
    
    // 如果API请求失败或没有时间段数据，使用模拟数据
    console.log('没有获取到有效的时间段数据，使用模拟数据')
    fallbackToMockTimeSlots()
  } catch (error) {
    console.error('加载时间段失败:', error)
    // 出错时使用模拟数据
    fallbackToMockTimeSlots()
  } finally {
    loading.value = false
  }
}

// 处理就诊类型变更
const handleVisitTypeChange = (value) => {
  // 重新过滤可用日期
  if (appointmentForm.appointmentDate) {
    // 检查已选日期在新的就诊类型下是否可用
    const selectedDate = availableDates.value.find(d => d.value === appointmentForm.appointmentDate)
    if (selectedDate && (!selectedDate.registrationTypes.includes(value))) {
      // 如果选中的日期不提供当前就诊类型，则清空选择
      appointmentForm.appointmentDate = ''
      appointmentForm.appointmentTime = ''
      morningSlots.value = []
      afternoonSlots.value = []
      ElMessage.warning('当前选择的日期不提供此就诊类型，请重新选择日期')
    }
  }
}

// 模拟日期数据（作为后备方案）
const fallbackToMockDates = () => {
  const dates = []
  const today = new Date()
  
  // 模拟的就诊类型
  const mockRegistrationTypes = ['general', 'specialist', 'expert']
  
  // 随机选择1-3种就诊类型
  const typesCount = Math.floor(Math.random() * 3) + 1
  const selectedTypes = []
  for (let i = 0; i < typesCount; i++) {
    const type = mockRegistrationTypes[Math.floor(Math.random() * mockRegistrationTypes.length)]
    if (!selectedTypes.includes(type)) {
      selectedTypes.push(type)
    }
  }
  
  // 更新可用就诊类型
  availableVisitTypes.value = selectedTypes.map(type => {
    return visitTypeOptions.value.find(opt => opt.value === type) || { value: type, label: type }
  })
  
  // 如果有可用的就诊类型但当前没有选择，则自动选择第一个
  if (availableVisitTypes.value.length > 0 && !appointmentForm.visitType) {
    appointmentForm.visitType = availableVisitTypes.value[0].value
  }
  
  // 生成从一周前到一周后的日期，共15天
  for (let i = -7; i <= 7; i++) {
    const date = new Date(today)
    date.setDate(today.getDate() + i)
    
    // 过去的日期不可预约
    const isPast = date < new Date().setHours(0, 0, 0, 0)
    
    // 所有使用模拟数据的日期都设为约满（剩余量为0）
    const remaining = 0
    
    // 为每一天随机分配就诊类型
    const dateTypes = []
    for (const type of selectedTypes) {
      if (Math.random() > 0.3) { // 70%概率该日期提供此就诊类型
        dateTypes.push(type)
      }
    }
    
    // 确保至少有一种就诊类型
    if (dateTypes.length === 0 && selectedTypes.length > 0) {
      dateTypes.push(selectedTypes[0])
    }
    
    // 检查是否包含当前选择的就诊类型
    const hasSelectedVisitType = !appointmentForm.visitType || dateTypes.includes(appointmentForm.visitType)
    
    dates.push({
      value: date.toISOString().split('T')[0],
      day: date.getDate(),
      month: `${date.getMonth() + 1}月`,
      weekday: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()],
      available: false, // 所有日期都设为不可用
      remaining: remaining,
      registrationTypes: dateTypes,
      isPast: isPast
    })
  }
  
  availableDates.value = dates
  console.log('使用模拟日期数据，所有日期都设为约满')
}

// 模拟时间段数据（作为后备方案）
const fallbackToMockTimeSlots = () => {
  console.log('使用模拟时间段数据，所有时间段都设为约满')
  
  // 上午时间段
  const morningTimes = [
    { value: '08:00-08:30', label: '08:00-08:30', period: '上午' },
    { value: '08:30-09:00', label: '08:30-09:00', period: '上午' },
    { value: '09:00-09:30', label: '09:00-09:30', period: '上午' },
    { value: '09:30-10:00', label: '09:30-10:00', period: '上午' },
    { value: '10:00-10:30', label: '10:00-10:30', period: '上午' },
    { value: '10:30-11:00', label: '10:30-11:00', period: '上午' },
    { value: '11:00-11:30', label: '11:00-11:30', period: '上午' },
    { value: '11:30-12:00', label: '11:30-12:00', period: '上午' }
  ]
  
  // 下午时间段
  const afternoonTimes = [
    { value: '13:30-14:00', label: '13:30-14:00', period: '下午' },
    { value: '14:00-14:30', label: '14:00-14:30', period: '下午' },
    { value: '14:30-15:00', label: '14:30-15:00', period: '下午' },
    { value: '15:00-15:30', label: '15:00-15:30', period: '下午' },
    { value: '15:30-16:00', label: '15:30-16:00', period: '下午' },
    { value: '16:00-16:30', label: '16:00-16:30', period: '下午' },
    { value: '16:30-17:00', label: '16:30-17:00', period: '下午' }
  ]
  
  // 所有时间段都设为已满
  morningSlots.value = morningTimes.map((slot, index) => ({
    ...slot,
    disabled: true, // 所有时段都设为不可用
    slotId: `mock-slot-${slot.period}-${index}`
  }))
  
  afternoonSlots.value = afternoonTimes.map((slot, index) => ({
    ...slot,
    disabled: true, // 所有时段都设为不可用
    slotId: `mock-slot-${slot.period}-${index}`
  }))
  
  console.log('模拟时间段数据生成完成，所有时间段都设为约满')
}

// 获取患者信息
const getPatientInfo = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  try {
    loading.value = true
    
    console.log('开始获取患者信息，用户存储信息:', {
      isLoggedIn: userStore.isLoggedIn,
      userInfo: userStore.userInfo,
      name: userStore.name,
      userRole: userStore.userRole
    })
    
    // 首先从API获取当前用户的详细信息
    const userId = userStore.userInfo.id || userStore.userInfo._id
    if (!userId) {
      console.error('无法获取用户ID')
      // 回退到从store加载基本信息
      loadBasicUserInfo()
      return
    }
    
    // 设置默认的patientId为userId(以防API调用失败)
    if (!userStore.userInfo.patientId) {
      console.log('设置默认patientId为用户ID:', userId)
      userStore.userInfo.patientId = userId
    }
    
    // 尝试获取与当前用户关联的患者信息
    const patientsRes = await patientAPI.getPatients({ userId: userId })
    
    console.log('患者API响应:', patientsRes)
    
    let patientData = null
    
    // 检查API返回数据
    if (patientsRes.success && patientsRes.data) {
      // 根据返回数据结构获取患者列表
      const patients = patientsRes.data.patients || patientsRes.data.items || []
      
      if (patients && patients.length > 0) {
        // 找到与用户ID匹配的患者记录
        patientData = patients.find(p => p.userId === userId)
        
        if (!patientData && patients.length > 0) {
          // 如果没有明确关联，使用第一个患者记录
          patientData = patients[0]
        }
      }
    }
    
    if (patientData) {
      console.log('找到患者记录:', patientData)
      
      // 确保设置patientId供后续提交使用
      if (patientData.id || patientData._id) {
        console.log('从API响应设置patientId:', patientData.id || patientData._id)
        userStore.userInfo.patientId = patientData.id || patientData._id
      }
      
      // 使用找到的患者信息填充表单
      appointmentForm.patientName = patientData.name || userStore.name || ''
      
      // 处理性别 - 转换为前端格式
      let gender = patientData.gender || ''
      if (gender === '男') appointmentForm.patientGender = 'male'
      else if (gender === '女') appointmentForm.patientGender = 'female'
      else appointmentForm.patientGender = 'male' // 默认值
      
      // 获取联系电话和身份证
      appointmentForm.patientPhone = patientData.contactInfo?.phone || patientData.phone || ''
      appointmentForm.patientID = patientData.idNumber || ''
    } else {
      console.warn('未找到患者记录，使用用户基本信息')
      // 如果没有找到患者记录，回退到基本用户信息
      loadBasicUserInfo()
    }
    
    // 检查用户信息是否完整
    if (!appointmentForm.patientName || !appointmentForm.patientPhone || !appointmentForm.patientID) {
      ElMessage.warning('您的个人信息不完整，建议在个人中心完善信息')
    }
    
    console.log('已加载用户信息作为患者信息:', appointmentForm)
  } catch (error) {
    console.error('获取患者信息失败:', error)
    ElMessage.warning('获取患者信息失败，使用基本信息')
    // 出错时回退到基本用户信息
    loadBasicUserInfo()
  } finally {
    loading.value = false
  }
}

// 从用户存储加载基本信息（作为备用方案）
const loadBasicUserInfo = () => {
  // 从用户存储中获取基本信息
  const userData = {
    name: userStore.userInfo?.name || userStore.name || '',
    gender: userStore.userInfo?.gender === '女' ? 'female' : 'male',
    phone: userStore.userInfo?.phone || userStore.userInfo?.phoneNumber || '',
    idNumber: userStore.userInfo?.idNumber || userStore.userInfo?.identityNumber || ''
  }
  
  console.log('从用户存储中获取的基本信息:', userData)
  console.log('用户存储完整信息:', {
    isLoggedIn: userStore.isLoggedIn,
    userInfo: userStore.userInfo,
    name: userStore.name,
    userRole: userStore.userRole
  })
  
  // 直接填充表单中的不可修改字段
  appointmentForm.patientName = userData.name || '未设置'
  appointmentForm.patientGender = userData.gender || 'male'
  appointmentForm.patientPhone = userData.phone || '未设置'
  appointmentForm.patientID = userData.idNumber || '未设置'
  
  // 检查是否能设置patientId - 为后续提交做准备
  if (userStore.userInfo && userStore.userInfo._id) {
    console.log('已找到用户ID:', userStore.userInfo._id)
    // 将用户ID保存到表单中
    userStore.userInfo.patientId = userStore.userInfo._id
  } else if (userStore.userInfo && userStore.userInfo.id) {
    console.log('已找到用户ID:', userStore.userInfo.id)
    // 将用户ID保存到表单中
    userStore.userInfo.patientId = userStore.userInfo.id
  } else {
    console.warn('未找到有效的用户ID，可能会导致预约提交失败')
  }
}

// 选择医生
const selectDoctor = (doctor) => {
  appointmentForm.doctorId = doctor.id
  
  // 选择医生后从API加载可预约日期
  generateAvailableDates(doctor.id)
}

// 处理菜单选择
const handleMenuSelect = (key) => {
  if (key !== 'appointment') {
    router.push(`/portal/patient/${key}`)
  }
}

// 更换医生
const changeDoctor = () => {
  activeStep.value = 0
}

// 选择时间段
const selectTimeSlot = (slot) => {
  if (!slot.disabled) {
    appointmentForm.appointmentTime = slot.value
  }
}

// 获取日期状态类
const getDateStatusClass = (date) => {
  if (!date.available) return 'status-disabled'
  if (date.remaining <= 5) return 'status-limited'
  return 'status-available'
}

// 获取日期状态文字
const getDateStatusText = (date) => {
  if (!date.available) return '约满'
  if (date.remaining <= 5) return '余量紧张'
  return '可预约'
}

// 获取科室标签
const getDepartmentLabel = (department) => {
  if (!department || department.length < 2) return ''
  
  const category = departmentOptions.value.find(option => option.value === department[0])
  if (!category) return ''
  
  const dept = category.children.find(child => child.value === department[1])
  if (!dept) return ''
  
  return `${category.label} - ${dept.label}`
}

// 获取日期标签
const getDateLabel = (dateValue) => {
  const date = availableDates.value.find(d => d.value === dateValue)
  return date ? `${date.value} ${date.weekday}` : ''
}

// 获取时间标签
const getTimeLabel = (timeValue) => {
  const morning = morningSlots.value.find(s => s.value === timeValue)
  if (morning) return morning.label
  
  const afternoon = afternoonSlots.value.find(s => s.value === timeValue)
  return afternoon ? afternoon.label : ''
}

// 获取就诊类型标签
const getVisitTypeLabel = (type) => {
  const types = {
    'expert': '专家门诊',
    'specialist': '专科门诊',
    'general': '普通门诊'
  }
  return types[type] || ''
}

// 提交患者信息
const submitPatientInfo = async () => {
  // 验证症状描述是否已填写
  if (!appointmentForm.symptoms || appointmentForm.symptoms.trim() === '') {
    ElMessage.error('请填写症状描述')
    return
  }
  
  try {
    loading.value = true
    
    // 尝试进行表单验证（如果表单引用存在）
    if (patientFormRef.value) {
      try {
        const isValid = await patientFormRef.value.validateField('symptoms')
          .then(() => true)
          .catch(() => false)
        
        if (!isValid) {
          ElMessage.error('请填写症状描述')
          return
        }
      } catch (error) {
        console.error('表单验证失败:', error)
        // 验证出错时，直接检查症状字段（已在函数开始处检查过）
      }
    }
    
    // 验证成功，进入下一步
    nextStep()
  } catch (error) {
    console.error('处理患者信息失败:', error)
    ElMessage.error('处理表单数据时出错，请稍后再试')
  } finally {
    loading.value = false
  }
}

// 确认预约
const confirmAppointment = () => {
  if (!agreementChecked.value) {
    ElMessage.warning('请阅读并同意服务条款和隐私保护政策')
    return
  }
  
  // 先检查症状描述是否已填写
  if (!appointmentForm.symptoms || appointmentForm.symptoms.trim() === '') {
    ElMessage.warning('请填写症状描述')
    return
  }
  
  ElMessageBox.confirm(
    '确认提交预约信息吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(() => {
    submitAppointment()
  }).catch(() => {
    // 用户取消
  })
}

// 提交预约到后端
const submitAppointment = async () => {
  if (!agreementChecked.value) {
    ElMessage.warning('请阅读并同意《预约须知》')
    return
  }
  
  // 表单验证 - 只验证症状描述字段
  try {
    // 检查表单引用是否存在
    if (!patientFormRef.value) {
      console.warn('表单引用不存在，跳过表单验证')
      // 直接检查症状描述是否填写
      if (!appointmentForm.symptoms || appointmentForm.symptoms.trim() === '') {
        ElMessage.error('请填写症状描述')
        return
      }
    } else {
      // 表单引用存在，使用表单验证
      const isValid = await patientFormRef.value.validateField('symptoms')
        .then(() => true)
        .catch(() => false)
      
      if (!isValid) {
        ElMessage.error('请填写症状描述')
        return
      }
    }
  } catch (error) {
    console.error('表单验证失败:', error)
    // 降级处理：如果表单验证出错，直接检查症状字段
    if (!appointmentForm.symptoms || appointmentForm.symptoms.trim() === '') {
      ElMessage.error('请填写症状描述')
      return
    }
  }
  
  loading.value = true
  
  try {
    // 查看用户存储中的信息
    console.log('用户存储中的信息:', {
      isLoggedIn: userStore.isLoggedIn,
      userInfo: userStore.userInfo,
      name: userStore.name,
      userRole: userStore.userRole,
      token: userStore.token ? '存在' : '不存在'
    })
    
    // 获取用户相关信息
    let patientId = null
    
    // 尝试多种方式获取患者ID
    if (userStore.userInfo && userStore.userInfo.patientId) {
      // 首选：直接从用户信息中获取患者ID
      patientId = userStore.userInfo.patientId
      console.log('从userInfo.patientId获取患者ID:', patientId)
    } else if (userStore.userInfo && userStore.userInfo.patient && userStore.userInfo.patient.id) {
      // 备选1：从patient对象获取ID
      patientId = userStore.userInfo.patient.id
      console.log('从userInfo.patient.id获取患者ID:', patientId)
    } else if (userStore.userInfo && userStore.userInfo._id) {
      // 备选2：使用用户ID作为患者ID
      patientId = userStore.userInfo._id
      console.log('使用用户ID(_id)作为患者ID:', patientId)
    } else if (userStore.userInfo && userStore.userInfo.id) {
      // 备选3：使用普通id
      patientId = userStore.userInfo.id
      console.log('使用用户ID(id)作为患者ID:', patientId)
    } else {
      // 最后尝试：生成一个临时ID（仅用于测试环境）
      console.warn('无法获取有效的患者ID，尝试使用备用方案')
      
      // 检查是否有患者名称，尝试使用它构建临时ID
      if (appointmentForm.patientName) {
        patientId = `temp-patient-${Date.now()}`
        console.log('使用临时生成的患者ID:', patientId)
      } else {
        // 如果确实无法获取ID，显示错误
        throw new Error('无法获取患者信息，请确保已登录或先完成个人信息设置')
      }
    }
    
    // 获取时间段和排班信息
    const selectedSlot = getSelectedTimeSlot()
    let scheduleId = null
    let period = '上午'
    
    if (selectedSlot && selectedSlot.slotId) {
      // 提取排班ID
      const parts = selectedSlot.slotId.split('-')
      if (parts.length > 0) {
        scheduleId = parts[0]
      }
      // 获取时段
      period = selectedSlot.period || '上午'
    }
    
    // 如果无法获取排班ID，可能需要模拟一个或报错
    if (!scheduleId) {
      console.warn('无法从时间段中获取排班ID，使用模拟数据')
      // 这里可以选择使用模拟ID或者报错中止预约
      scheduleId = `mock-schedule-${Date.now()}`
    }
    
    // 构造预约数据，严格按照后端API要求的格式
    const appointmentData = {
      patientId: patientId,
      scheduleId: scheduleId,
      doctorId: appointmentForm.doctorId,
      departmentId: appointmentForm.department[1],
      appointmentDate: appointmentForm.appointmentDate,
      timeSlot: appointmentForm.appointmentTime,
      period: period,
      visitType: '初诊', // 默认初诊
      registrationType: appointmentForm.visitType === 'expert' ? '专家门诊' : 
                        appointmentForm.visitType === 'general' ? '普通门诊' : 
                        appointmentForm.visitType === 'specialist' ? '特需门诊' : appointmentForm.visitType,
      remarks: appointmentForm.symptoms // 使用症状描述作为备注信息
    }
    
    console.log('提交预约数据:', appointmentData)
    
    // 调用创建预约API
    const res = await appointmentAPI.createAppointment(appointmentData)
    
    if (res.success) {
      // 生成预约号
      appointmentNumber.value = res.data?.appointmentId || res.data?.appointmentNumber || `A${Date.now().toString().substr(-8)}`
      
      // 保存预约信息到localStorage，供"我的预约"页面使用
      const appointmentInfo = {
        appointmentNumber: appointmentNumber.value,
        departmentName: getDepartmentLabel(appointmentForm.department),
        doctorName: selectedDoctor.value ? `${selectedDoctor.value.name} ${selectedDoctor.value.title}` : '未知医生',
        appointmentDate: appointmentForm.appointmentDate,
        appointmentTime: appointmentForm.appointmentTime,
        status: 'pending', // 初始状态为待确认
        date: new Date().toISOString(),
        visitType: appointmentForm.visitType,
        patientName: appointmentForm.patientName,
        patientGender: appointmentForm.patientGender,
        patientPhone: appointmentForm.patientPhone,
        symptoms: appointmentForm.symptoms,
        patientId: patientId
      }
      
      // 保存到localStorage
      localStorage.setItem('lastAppointment', JSON.stringify(appointmentInfo))
      console.log('预约信息已保存到本地:', appointmentInfo)
      
      nextStep()
      ElMessage.success('预约成功')
    } else {
      throw new Error(res.message || '预约提交失败')
    }
  } catch (error) {
    console.error('提交预约失败:', error)
    ElMessage.error(error.message || '预约失败，请稍后再试')
  } finally {
    loading.value = false
  }
}

// 获取选中的时间段对象
const getSelectedTimeSlot = () => {
  if (!appointmentForm.appointmentTime) return null
  
  // 在上午时间段中查找
  const morningSlot = morningSlots.value.find(slot => slot.value === appointmentForm.appointmentTime)
  if (morningSlot) return morningSlot
  
  // 在下午时间段中查找
  const afternoonSlot = afternoonSlots.value.find(slot => slot.value === appointmentForm.appointmentTime)
  return afternoonSlot || null
}

// 下一步
const nextStep = () => {
  activeStep.value++
}

// 上一步
const prevStep = () => {
  activeStep.value--
}

// 跳转到预约列表
const navigateToAppointmentList = () => {
  router.push('/portal/patient/appointments')
}

// 跳转到首页
const navigateToHome = () => {
  router.push('/portal')
}

// 页面加载
onMounted(async () => {
  console.log('预约页面加载')
  
  // 获取用户和患者信息
  await getPatientInfo()
  
  // 获取部门和医生数据
  await loadDepartments()
})

// 添加获取科室名称的方法
// 获取科室名称（只返回名称不带分类）
const getDepartmentName = (department) => {
  if (!department || department.length < 2) return ''
  
  const category = departmentOptions.value.find(option => option.value === department[0])
  if (!category) return ''
  
  const dept = category.children.find(child => child.value === department[1])
  if (!dept) return ''
  
  return dept.label
}

// 选择就诊日期
const selectDate = (date) => {
  if (date.available) {
    appointmentForm.appointmentDate = date.value
    appointmentForm.appointmentTime = '' // 清空时间选择
    
    // 更新当前选择日期的就诊类型（如果需要的话）
    if (date.registrationTypes && date.registrationTypes.length > 0) {
      // 如果当前选择的就诊类型在该日期不可用，则自动选择该日期的第一个就诊类型
      if (!date.registrationTypes.includes(appointmentForm.visitType)) {
        appointmentForm.visitType = date.registrationTypes[0]
        
        // 获取类型对应的标签
        let typeLabel = appointmentForm.visitType
        if (appointmentForm.visitType === 'general') {
          typeLabel = '普通门诊'
        } else if (appointmentForm.visitType === 'expert') {
          typeLabel = '专家门诊'
        } else if (appointmentForm.visitType === 'specialist') {
          typeLabel = '特需门诊'
        }
        
        ElMessage.info(`已自动切换为该日期可用的就诊类型: ${typeLabel}`)
      }
    }
    
    // 日期变更后从API加载时间段
    generateTimeSlots(date.value, appointmentForm.doctorId)
  }
}
</script>

<style scoped>
.appointment-page {
  background-color: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 40px;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  background-color: white;
  padding: 20px 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 30px;
}

.page-title {
  font-size: 24px;
  color: #333;
  margin: 0 0 10px;
}

.main-content {
  margin-bottom: 40px;
}

.side-nav {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.side-nav-title {
  font-size: 18px;
  margin: 0;
  padding: 20px;
  background: #1989fa;
  color: white;
}

.side-menu {
  border-right: none;
}

.service-card {
  padding: 20px;
  background: #f0f9ff;
  margin-top: 20px;
  border-radius: 0 0 8px 8px;
}

.service-card-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  margin: 0 0 10px;
  color: #1989fa;
}

.service-card-title .el-icon {
  margin-right: 5px;
}

.service-phone {
  font-size: 20px;
  font-weight: bold;
  margin: 10px 0;
  color: #333;
}

.service-time {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.appointment-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

.alert-info {
  margin-bottom: 30px;
}

.appointment-steps {
  margin-bottom: 40px;
}

.step-container {
  padding: 20px 0;
}

.step-title {
  font-size: 20px;
  margin: 0 0 30px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.section-subtitle {
  font-size: 16px;
  margin: 30px 0 20px;
  color: #666;
}

.doctor-list {
  margin-top: 30px;
}

.doctor-card {
  display: flex;
  padding: 15px; /* 减少内边距 */
  background: #f9f9f9;
  border-radius: 8px;
  margin-bottom: 15px; /* 减少卡片间距 */
  cursor: pointer;
  transition: all 0.3s;
  border: 2px solid transparent;
  height: 150px; /* 将高度从180px缩小到150px */
  width: 100%;   /* 固定宽度为100% */
  box-sizing: border-box;
  align-items: flex-start; /* 将对齐方式改为顶部对齐 */
}

.doctor-card:hover {
  background: #f0f7ff;
}

.doctor-card-selected {
  border-color: #1989fa;
  background: #f0f7ff;
}

.doctor-avatar {
  margin-right: 15px;
  flex-shrink: 0; /* 防止头像被挤压 */
}

.doctor-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: flex-start; /* 从顶部开始排列内容 */
  height: 100%; /* 撑满容器高度 */
}

.doctor-name {
  font-size: 18px;
  margin: 0 0 3px; /* 减小底部margin */
  color: #333;
  font-weight: bold;
}

.doctor-title {
  font-size: 14px;
  color: #1989fa;
  margin: 0 0 5px; /* 减小底部margin */
  font-weight: normal;
}

.doctor-specialty {
  color: #666;
  font-size: 14px;
  margin: 0 0 5px; /* 再减小底部margin */
}

.doctor-rating {
  margin-top: 3px; /* 进一步减小与上方内容的距离 */
  padding-top: 0;
}

.doctor-rating .el-rate {
  height: 20px; /* 设置评分组件高度 */
  line-height: 1;
}

.doctor-selected {
  display: flex;
  align-items: center;
  background: #f0f7ff;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.doctor-selected-avatar {
  margin-right: 15px;
}

.doctor-selected-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.doctor-selected-name {
  font-size: 16px;
  margin: 0 0 5px;
  color: #333;
  font-weight: bold;
}

.doctor-selected-title {
  font-size: 14px;
  color: #1989fa;
  margin: 0 0 5px;
  font-weight: normal;
}

.doctor-selected-dept {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.date-selection {
  margin-bottom: 30px;
}

.date-selector {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.date-item {
  width: calc(100% / 7 - 15px);
  min-width: 100px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  padding: 15px 10px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  border: 2px solid transparent;
}

.date-item:hover:not(.date-disabled) {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.date-selected {
  border-color: #1989fa;
  background: #f0f7ff;
}

.date-disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.date-past {
  background: #f5f5f5;
  opacity: 0.6;
  cursor: not-allowed;
}

.date-weekday {
  color: #666;
  font-size: 14px;
  margin-bottom: 5px;
}

.date-day {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.date-month {
  color: #666;
  font-size: 14px;
  margin-bottom: 8px;
}

.date-status {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 10px;
  display: inline-block;
}

.status-available {
  background: #e1f3d8;
  color: #67c23a;
}

.status-limited {
  background: #fdf6ec;
  color: #e6a23c;
}

.status-disabled {
  background: #f4f4f5;
  color: #909399;
}

.time-selection {
  margin-bottom: 30px;
}

.time-period {
  margin-bottom: 20px;
}

.period-title {
  font-size: 15px;
  margin: 0 0 15px;
  color: #606266;
  position: relative;
  padding-left: 12px;
}

.period-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 16px;
  background-color: #1989fa;
  border-radius: 2px;
}

.time-slots {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.time-slot {
  width: calc(25% - 10px);
  min-width: 120px;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
  text-align: center;
  cursor: pointer;
  transition: all 0.2s;
}

.time-slot:hover:not(.time-slot-disabled) {
  border-color: #1989fa;
  color: #1989fa;
}

.time-slot-selected {
  background: #ecf5ff;
  border-color: #1989fa;
  color: #1989fa;
}

.time-slot-disabled {
  background: #f5f7fa;
  color: #c0c4cc;
  cursor: not-allowed;
}

.time-text {
  display: block;
  font-size: 14px;
  margin-bottom: 5px;
}

.slot-status {
  display: block;
  font-size: 12px;
  color: #909399;
}

.time-slot-selected .slot-status {
  color: #1989fa;
}

.step-actions {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.appointment-summary {
  background: #f9f9f9;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 30px;
}

.summary-item {
  margin-bottom: 10px;
  display: flex;
}

.summary-item:last-child {
  margin-bottom: 0;
}

.summary-label {
  font-weight: bold;
  min-width: 100px;
  color: #606266;
}

.summary-value {
  color: #333;
  flex: 1;
}

.patient-form {
  max-width: 600px;
  margin: 0 auto;
}

.confirmation-card {
  border-radius: 8px;
  border: 1px solid #ebeef5;
  background-color: #fff;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.confirmation-header {
  background-color: #f5f7fa;
  padding: 20px;
  display: flex;
  align-items: center;
}

.confirmation-icon {
  font-size: 24px;
  color: #1989fa;
  margin-right: 10px;
}

.confirmation-title {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.confirmation-content {
  padding: 20px;
}

.confirmation-section {
  margin-bottom: 20px;
}

.confirmation-section:last-child {
  margin-bottom: 0;
}

.confirmation-section-title {
  font-size: 16px;
  color: #606266;
  margin: 0 0 15px;
  padding-bottom: 10px;
  border-bottom: 1px dashed #ebeef5;
}

.confirmation-item {
  margin-bottom: 10px;
  display: flex;
}

.confirmation-label {
  width: 100px;
  color: #909399;
}

.confirmation-value {
  flex: 1;
  color: #303133;
}

.confirmation-text {
  color: #606266;
  line-height: 1.6;
  margin: 0;
}

.confirmation-footer {
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
}

.success-container {
  background: white;
  border-radius: 8px;
  padding: 30px;
  text-align: center;
}

.success-info {
  background: #f9f9f9;
  border-radius: 8px;
  padding: 20px;
  text-align: left;
  max-width: 500px;
  margin: 0 auto 30px;
}

.success-info p {
  margin: 10px 0;
  color: #606266;
}

.success-actions {
  margin-top: 30px;
}

.no-visit-type-tip {
  color: #909399;
  font-size: 14px;
  margin-top: 8px;
  font-style: italic;
}

@media (max-width: 768px) {
  .appointment-content {
    padding: 20px;
  }
  
  .side-nav {
    margin-bottom: 20px;
  }
  
  .date-item {
    width: calc(33.33% - 10px);
  }
  
  .time-slot {
    width: calc(50% - 5px);
  }
}

@media (max-width: 576px) {
  .date-item {
    width: calc(50% - 10px);
  }
  
  .time-slot {
    width: 100%;
  }
  
  .doctor-selected {
    flex-direction: column;
    text-align: center;
  }
  
  .doctor-selected-avatar {
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .doctor-selected-action {
    margin-top: 10px;
  }
}

.full-width-cascader {
  width: 100%;
}

.el-cascader {
  width: 100%;
}

.el-cascader-panel {
  display: flex;
}

.el-cascader-menu {
  min-width: 180px;
  height: 300px;
}

.el-cascader-menu__wrap {
  padding: 0;
}

/* 调整就诊类型选择器布局 */
.el-radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

/* 调整科室选择表单布局 */
.el-form-item {
  margin-bottom: 20px;
}

/* 调整步骤1的整体布局 */
.step-container .el-form {
  max-width: 600px;
  margin: 0 auto 30px;
}

/* 使科室选择器更紧凑 */
.el-cascader-menu__list {
  padding: 0;
}

.el-cascader-node {
  padding: 10px 15px;
}

.el-cascader-node__label {
  flex: 1;
  padding-right: 10px;
}

.el-popper.el-cascader__dropdown {
  min-width: 400px;
}

.form-item-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style> 